/**
 * 
 */
package lt.ruta.ui;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.List;

import lt.ruta.RutaMidlet;
import lt.ruta.Utils;

/**
 * @author Vincentas
 *
 */
public class DirectoryForm extends List {
	
	private String path = null;
	
	public DirectoryForm(String title) {
		super(title, List.IMPLICIT);
		setPath(null);
	}
		
	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	public String getSelectedPath() {
		String result = path;
		
		if (result == null) {
			result = "";
		}		
		
		if (getSelectedIndex() != -1) {
			result += getString(getSelectedIndex());
		}
		
		return result;
	}
	
	public void setPath(String path) {
		this.path = path;
		deleteAll();
		
		if (path == null || path.length() == 0) {
			Enumeration roots = FileSystemRegistry.listRoots();
			while (roots.hasMoreElements()) {
				String root = (String) roots.nextElement();
				append(root, null);
			}
		} else {
			try {
				FileConnection fileConnection = (FileConnection) Connector.open("file:///" + path);
				Enumeration files = fileConnection.list();
				while (files.hasMoreElements()) {					
					String fileName = (String) files.nextElement();
					if (isFolder(fileName)) {
						append(fileName, null);
					}				
				}
			} catch (IOException exception) {
				RutaMidlet.instance.showError(exception);
			} catch (SecurityException securityException) {
				RutaMidlet.instance.showError(securityException);
			}
		}
	}
	
	private boolean isFolder(String fileName) {
		return fileName.indexOf('/') == fileName.length() - 1;
	}

	/**
	 * 
	 */
	public static String getParent(String path) {
		if (path != null) {
			String[] parts = Utils.split(path, '/');
			String newPath = "";
			for (int i = 0; i < parts.length - 2; i++) {
				newPath += parts[i] + '/';
			}
			
			path = newPath;
		}
		
		return path;
	}	
}
